package com.migrate.module.config;

import com.migrate.module.sharding.MigrateConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * 目标数据源配置
 *
 * @author zhonghuashishan
 */
@Slf4j
@Configuration
@MapperScan(basePackages = "com.migrate.module.mapper.db2", sqlSessionTemplateRef = "SqlSessionTemplate02")
public class DataSource2Config extends AbstractDataSourceConfig {
    @Autowired
    private MigrateConfig migrateConfig;

    @Bean(name = "DataSource02")
    public DataSource dataSource() throws SQLException {
        return buildDataSource(migrateConfig.getTargetDatasource());
    }

    @Bean(name = "SqlSessionFactory02")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("DataSource02") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage("com.migrate.module.domain");
        bean.setConfigLocation(new ClassPathResource("mybatis/mybatis-config.xml"));
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/mapper/db2/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "transactionManager02")
    public DataSourceTransactionManager transactionManager(@Qualifier("DataSource02") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "SqlSessionTemplate02")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("SqlSessionFactory02") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
